/**
 * useAnnotations Composable
 * 
 * 用于管理标注数据的 Vue 组合式函数
 * 
 * @author yangzhixin
 * @module composables/useAnnotations
 */

import { ref, computed, type Ref } from 'vue';
import type { CornerstoneFacade } from 'js-3d-model';

/**
 * 标注类型枚举
 */
export enum AnnotationType {
  Length = 'Length',
  Angle = 'Angle',
  Rectangle = 'RectangleROI',
  Ellipse = 'EllipticalROI',
  Circle = 'CircleROI',
  Bidirectional = 'Bidirectional',
  Arrow = 'ArrowAnnotate',
  Probe = 'Probe',
  Freehand = 'FreehandROI',
}

/**
 * 标注数据接口
 */
export interface Annotation {
  /** 标注唯一ID */
  annotationUID: string;
  /** 工具名称 */
  toolName: string;
  /** 标注数据 */
  data: any;
  /** 元数据 */
  metadata?: {
    /** 创建时间 */
    createdAt?: string;
    /** 修改时间 */
    modifiedAt?: string;
    /** 创建者 */
    createdBy?: string;
    /** 标签 */
    label?: string;
    /** 描述 */
    description?: string;
    /** 自定义数据 */
    [key: string]: any;
  };
}

/**
 * 标注过滤选项
 */
export interface AnnotationFilterOptions {
  /** 工具名称 */
  toolName?: string;
  /** 标签 */
  label?: string;
  /** 创建者 */
  createdBy?: string;
  /** 开始日期 */
  startDate?: string;
  /** 结束日期 */
  endDate?: string;
}

/**
 * 标注统计信息
 */
export interface AnnotationStats {
  /** 总数 */
  total: number;
  /** 按工具分类的数量 */
  byTool: Record<string, number>;
  /** 按标签分类的数量 */
  byLabel: Record<string, number>;
}

/**
 * useAnnotations 返回类型
 */
export interface UseAnnotationsReturn {
  /** 所有标注 */
  annotations: Ref<Annotation[]>;
  /** 过滤后的标注 */
  filteredAnnotations: Ref<Annotation[]>;
  /** 选中的标注 */
  selectedAnnotations: Ref<Annotation[]>;
  /** 标注统计 */
  stats: Ref<AnnotationStats>;
  /** 是否正在加载 */
  isLoading: Ref<boolean>;
  /** 错误信息 */
  error: Ref<string | null>;
  /** 加载所有标注 */
  loadAnnotations: (toolName?: string) => Promise<void>;
  /** 添加标注 */
  addAnnotation: (annotation: Annotation) => void;
  /** 更新标注 */
  updateAnnotation: (annotationUID: string, updates: Partial<Annotation>) => Promise<void>;
  /** 删除标注 */
  deleteAnnotation: (annotationUID: string) => Promise<void>;
  /** 批量删除标注 */
  deleteAnnotations: (annotationUIDs: string[]) => Promise<void>;
  /** 选择标注 */
  selectAnnotation: (annotationUID: string) => void;
  /** 取消选择标注 */
  deselectAnnotation: (annotationUID: string) => void;
  /** 清空选择 */
  clearSelection: () => void;
  /** 过滤标注 */
  filterAnnotations: (options: AnnotationFilterOptions) => void;
  /** 清除过滤 */
  clearFilter: () => void;
  /** 导出标注 */
  exportAnnotations: (format?: 'json' | 'csv') => Promise<string>;
  /** 导入标注 */
  importAnnotations: (data: string, format?: 'json' | 'csv') => Promise<void>;
  /** 保存标注到本地 */
  saveToLocal: (key: string) => Promise<void>;
  /** 从本地加载标注 */
  loadFromLocal: (key: string) => Promise<void>;
}

/**
 * useAnnotations - 标注管理
 * 
 * 提供响应式的标注管理，包括增删改查、过滤、导入导出等功能
 * 
 * @param facade - CornerstoneFacade 实例
 * @returns 标注管理方法和状态
 * 
 * @example
 * ```vue
 * <script setup>
 * import { useAnnotations } from '@/composables/useAnnotations';
 * import { useCornerstone3D } from '@/composables/useCornerstone3D';
 * 
 * const { facade } = useCornerstone3D();
 * const { 
 *   annotations, 
 *   loadAnnotations, 
 *   deleteAnnotation 
 * } = useAnnotations(facade);
 * 
 * onMounted(async () => {
 *   await loadAnnotations();
 * });
 * </script>
 * ```
 */
export function useAnnotations(
  facade: Ref<CornerstoneFacade | null>
): UseAnnotationsReturn {
  // 响应式状态
  const annotations = ref<Annotation[]>([]);
  const filteredAnnotations = ref<Annotation[]>([]);
  const selectedAnnotations = ref<Annotation[]>([]);
  const isLoading = ref(false);
  const error = ref<string | null>(null);

  // 当前过滤选项
  let currentFilter: AnnotationFilterOptions | null = null;

  // 计算统计信息
  const stats = computed<AnnotationStats>(() => {
    const total = annotations.value.length;
    const byTool: Record<string, number> = {};
    const byLabel: Record<string, number> = {};

    annotations.value.forEach((annotation) => {
      // 按工具统计
      if (annotation.toolName) {
        byTool[annotation.toolName] = (byTool[annotation.toolName] || 0) + 1;
      }

      // 按标签统计
      const label = annotation.metadata?.label || 'unlabeled';
      byLabel[label] = (byLabel[label] || 0) + 1;
    });

    return { total, byTool, byLabel };
  });

  /**
   * 加载所有标注
   * 
   * @param toolName - 可选的工具名称过滤
   */
  const loadAnnotations = async (toolName?: string): Promise<void> => {
    if (!facade.value) {
      throw new Error('Cornerstone3D 未初始化');
    }

    try {
      isLoading.value = true;
      error.value = null;

      console.log('[useAnnotations] 加载标注:', toolName);

      const result = await facade.value.getAllAnnotations({
        toolName,
      });

      annotations.value = result || [];
      filteredAnnotations.value = annotations.value;

      console.log(`[useAnnotations] 加载了 ${annotations.value.length} 个标注`);
    } catch (err: any) {
      console.error('[useAnnotations] 加载标注失败:', err);
      error.value = err.message || '加载标注失败';
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 添加标注（仅更新本地状态）
   * 
   * @param annotation - 标注数据
   */
  const addAnnotation = (annotation: Annotation): void => {
    annotations.value.push(annotation);
    applyCurrentFilter();
  };

  /**
   * 更新标注
   * 
   * @param annotationUID - 标注ID
   * @param updates - 更新的数据
   */
  const updateAnnotation = async (
    annotationUID: string,
    updates: Partial<Annotation>
  ): Promise<void> => {
    try {
      console.log('[useAnnotations] 更新标注:', annotationUID);

      const index = annotations.value.findIndex(
        (a) => a.annotationUID === annotationUID
      );

      if (index === -1) {
        throw new Error(`标注不存在: ${annotationUID}`);
      }

      // 更新本地数据
      annotations.value[index] = {
        ...annotations.value[index],
        ...updates,
        metadata: {
          ...annotations.value[index].metadata,
          ...updates.metadata,
          modifiedAt: new Date().toISOString(),
        },
      };

      applyCurrentFilter();

      console.log('[useAnnotations] 标注更新成功');
    } catch (err: any) {
      console.error('[useAnnotations] 更新标注失败:', err);
      error.value = err.message || '更新标注失败';
      throw err;
    }
  };

  /**
   * 删除标注
   * 
   * @param annotationUID - 标注ID
   */
  const deleteAnnotation = async (annotationUID: string): Promise<void> => {
    if (!facade.value) {
      throw new Error('Cornerstone3D 未初始化');
    }

    try {
      console.log('[useAnnotations] 删除标注:', annotationUID);

      await facade.value.removeAnnotation({
        annotationUID,
      });

      // 从本地列表中移除
      annotations.value = annotations.value.filter(
        (a) => a.annotationUID !== annotationUID
      );

      // 从选中列表中移除
      selectedAnnotations.value = selectedAnnotations.value.filter(
        (a) => a.annotationUID !== annotationUID
      );

      applyCurrentFilter();

      console.log('[useAnnotations] 标注删除成功');
    } catch (err: any) {
      console.error('[useAnnotations] 删除标注失败:', err);
      error.value = err.message || '删除标注失败';
      throw err;
    }
  };

  /**
   * 批量删除标注
   * 
   * @param annotationUIDs - 标注ID数组
   */
  const deleteAnnotations = async (annotationUIDs: string[]): Promise<void> => {
    try {
      console.log(`[useAnnotations] 批量删除 ${annotationUIDs.length} 个标注`);

      for (const uid of annotationUIDs) {
        await deleteAnnotation(uid);
      }

      console.log('[useAnnotations] 批量删除成功');
    } catch (err: any) {
      console.error('[useAnnotations] 批量删除失败:', err);
      error.value = err.message || '批量删除失败';
      throw err;
    }
  };

  /**
   * 选择标注
   * 
   * @param annotationUID - 标注ID
   */
  const selectAnnotation = (annotationUID: string): void => {
    const annotation = annotations.value.find(
      (a) => a.annotationUID === annotationUID
    );

    if (annotation && !selectedAnnotations.value.includes(annotation)) {
      selectedAnnotations.value.push(annotation);
    }
  };

  /**
   * 取消选择标注
   * 
   * @param annotationUID - 标注ID
   */
  const deselectAnnotation = (annotationUID: string): void => {
    selectedAnnotations.value = selectedAnnotations.value.filter(
      (a) => a.annotationUID !== annotationUID
    );
  };

  /**
   * 清空选择
   */
  const clearSelection = (): void => {
    selectedAnnotations.value = [];
  };

  /**
   * 应用当前过滤器
   */
  const applyCurrentFilter = (): void => {
    if (!currentFilter) {
      filteredAnnotations.value = annotations.value;
      return;
    }

    filteredAnnotations.value = annotations.value.filter((annotation) => {
      // 工具名称过滤
      if (
        currentFilter.toolName &&
        annotation.toolName !== currentFilter.toolName
      ) {
        return false;
      }

      // 标签过滤
      if (
        currentFilter.label &&
        annotation.metadata?.label !== currentFilter.label
      ) {
        return false;
      }

      // 创建者过滤
      if (
        currentFilter.createdBy &&
        annotation.metadata?.createdBy !== currentFilter.createdBy
      ) {
        return false;
      }

      // 日期范围过滤
      if (currentFilter.startDate || currentFilter.endDate) {
        const createdAt = annotation.metadata?.createdAt;
        if (!createdAt) return false;

        if (currentFilter.startDate && createdAt < currentFilter.startDate) {
          return false;
        }

        if (currentFilter.endDate && createdAt > currentFilter.endDate) {
          return false;
        }
      }

      return true;
    });
  };

  /**
   * 过滤标注
   * 
   * @param options - 过滤选项
   */
  const filterAnnotations = (options: AnnotationFilterOptions): void => {
    currentFilter = options;
    applyCurrentFilter();
  };

  /**
   * 清除过滤
   */
  const clearFilter = (): void => {
    currentFilter = null;
    filteredAnnotations.value = annotations.value;
  };

  /**
   * 导出标注
   * 
   * @param format - 导出格式
   * @returns 标注数据字符串
   */
  const exportAnnotations = async (
    format: 'json' | 'csv' = 'json'
  ): Promise<string> => {
    if (!facade.value) {
      throw new Error('Cornerstone3D 未初始化');
    }

    try {
      console.log('[useAnnotations] 导出标注:', format);

      const data = await facade.value.exportAnnotations({
        format,
      });

      console.log('[useAnnotations] 标注导出成功');
      return data;
    } catch (err: any) {
      console.error('[useAnnotations] 导出标注失败:', err);
      error.value = err.message || '导出标注失败';
      throw err;
    }
  };

  /**
   * 导入标注
   * 
   * @param data - 标注数据字符串
   * @param format - 数据格式
   */
  const importAnnotations = async (
    data: string,
    format: 'json' | 'csv' = 'json'
  ): Promise<void> => {
    if (!facade.value) {
      throw new Error('Cornerstone3D 未初始化');
    }

    try {
      console.log('[useAnnotations] 导入标注:', format);

      await facade.value.importAnnotations({
        data,
        format,
      });

      // 重新加载标注
      await loadAnnotations();

      console.log('[useAnnotations] 标注导入成功');
    } catch (err: any) {
      console.error('[useAnnotations] 导入标注失败:', err);
      error.value = err.message || '导入标注失败';
      throw err;
    }
  };

  /**
   * 保存标注到本地存储
   * 
   * @param key - 存储键名
   */
  const saveToLocal = async (key: string): Promise<void> => {
    if (!facade.value) {
      throw new Error('Cornerstone3D 未初始化');
    }

    try {
      console.log('[useAnnotations] 保存标注到本地:', key);

      await facade.value.saveAnnotationsToLocal({
        key,
        annotations: annotations.value,
      });

      console.log('[useAnnotations] 标注保存成功');
    } catch (err: any) {
      console.error('[useAnnotations] 保存标注失败:', err);
      error.value = err.message || '保存标注失败';
      throw err;
    }
  };

  /**
   * 从本地存储加载标注
   * 
   * @param key - 存储键名
   */
  const loadFromLocal = async (key: string): Promise<void> => {
    if (!facade.value) {
      throw new Error('Cornerstone3D 未初始化');
    }

    try {
      console.log('[useAnnotations] 从本地加载标注:', key);

      const result = await facade.value.loadAnnotationsFromLocal({
        key,
      });

      annotations.value = result || [];
      filteredAnnotations.value = annotations.value;

      console.log(`[useAnnotations] 从本地加载了 ${annotations.value.length} 个标注`);
    } catch (err: any) {
      console.error('[useAnnotations] 加载标注失败:', err);
      error.value = err.message || '加载标注失败';
      throw err;
    }
  };

  return {
    annotations,
    filteredAnnotations,
    selectedAnnotations,
    stats,
    isLoading,
    error,
    loadAnnotations,
    addAnnotation,
    updateAnnotation,
    deleteAnnotation,
    deleteAnnotations,
    selectAnnotation,
    deselectAnnotation,
    clearSelection,
    filterAnnotations,
    clearFilter,
    exportAnnotations,
    importAnnotations,
    saveToLocal,
    loadFromLocal,
  };
}


